package com.sc.nft.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.sc.nft.config.Bank4ValidateConfig;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.sup.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public final class BankUtil {

  public static JSONObject card4Validate(
      Bank4ValidateConfig config,
      String bankCard,
      String idCard,
      String name,
      String phone) {

    Calendar cd = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    String datetime = sdf.format(cd.getTime());
    String auth = BankUtil.calcAuthorization(datetime, config.getSecretId(), config.getSecretKey());
    Map<String, Object> bodyParams = new HashMap<>();
    bodyParams.put("bankCardNo", bankCard);
    bodyParams.put("idCardNo", idCard);
    bodyParams.put("mobile", phone);
    bodyParams.put("name", name);
    String result =
        HttpRequest.post(config.getUrl())
            .header("X-Source", "market")
            .header("X-Date", datetime)
            .header("Authorization", auth)
            .form(bodyParams)
            .execute()
            .body();
    return JSONObject.parseObject(result);
  }

  private static String calcAuthorization(String datetime, String secretId, String secretKey) {
    String signStr = "x-date: " + datetime + "\n" + "x-source: market";
    try {
      Mac mac = Mac.getInstance("HmacSHA1");
      Key sKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
      mac.init(sKey);
      byte[] hash = mac.doFinal(signStr.getBytes(StandardCharsets.UTF_8));
      String sig = new BASE64Encoder().encode(hash);
      String auth =
          "hmac id=\""
              + secretId
              + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\""
              + sig
              + "\"";
      return auth;
    } catch (Exception e) {
      log.error("bank util签名计算错误，", e);
      throw new GlobalRunTimeException(ErrorCode.SYS_ERROR);
    }
  }

  private static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<?, ?> entry : map.entrySet()) {
      if (sb.length() > 0) {
        sb.append("&");
      }
      sb.append(
          String.format(
              "%s=%s",
              URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
              URLEncoder.encode(entry.getValue().toString(), "UTF-8")));
    }
    return sb.toString();
  }
}
